import json
import sys
import copy

def convert(menuFile, urlFile):
    with open(menuFile) as f:
        root = json.load(f)

    with open(urlFile) as urlF:
        urls = json.load(urlF)

    webUrls = {}
    for url in urls:
        webUrls = dict(webUrls, ** url)
    
    allkeys = []
    allMenuItems = []
    for firstLevel in root:
        subMenu1 = firstLevel["submenu"]
        for secondMenu in subMenu1:
            thirdMenu = secondMenu.get("submenu")
            if thirdMenu is None:
                continue
            allMenuItems += copy.deepcopy(list(thirdMenu))
            for menu in thirdMenu:
                id = menu["id"]
                title = menu["title"]
                menu.clear()
                menu["id"] = id
                menu["title"] = title
                

    cmds = []
    webCmd = {"id":77000, "name":"WebCommand"}
    cmds.append(webCmd)

    hout = open(r"C:\code\qeubee-x\source\qbbond\CmdDefines.h", 'w', encoding='utf-8')
    for item in allMenuItems:
        for key in item.keys():
            if key not in allkeys:
                allkeys.append(key)
        cmd = {}
        cmd["id"] = item["id"]
        cmd["name"] = item["ename"]
        if item["id"] >= 77000 or "woption" in item:
            cmd["baseCmd"] = 77000
            cmd["module"]="qbbond"

        cmds.append(cmd)

        name = cmd["name"]
        name = name.replace(" ", "_")
        name = name.replace("-", "_")
        name = name.replace(".", "_")
        line = "#define CMD_" + name + "        " + str(cmd["id"]) +  " //" + item["title"] + "\n"
        hout.write(line)
    
    hout.close()
    with open(r"C:\code\qeubee-x\resource\config\cmds.cfg", 'w', encoding='utf-8') as out:
        jdata = json.dump(cmds, out,ensure_ascii=False, indent="\t")

convert(r"C:\Sumscope\Qeubee\config\menu.json", r"C:\Sumscope\Qeubee\config\woptions.json")


